package com.moli.iov.admin.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.moli.iov.admin.component.CacheManger;
import com.moli.iov.admin.constants.Constants;
import com.moli.iov.rest.GenericCode;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.constants.Constant;
import com.moli.iov.util.JwtTokenUtil;
import com.moli.iov.util.ResponseUtils;
import com.moli.iov.util.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * <p>
 * 登陆拦截器
 * </p>
 *
 * @author zql
 * @since 2019/9/20 10:43
 */
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {


  @Value("${jwt.tokenHeader}")
  private String jwtTokenHeader;

  @Value("${jwt.tokenHead}")
  private String tokenHead;

  @Value("${pwd.salt}")
  private String salt;

  @Autowired
  private CacheManger cacheManger;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    try {
      String authHeader = request.getHeader(jwtTokenHeader);

      if (StringUtil.isBlank(authHeader) || !authHeader.startsWith(this.tokenHead)) {
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.LOGOUT_NOTICE)), Constants.RESPONSE_STATUS);
        return false;
      }

      String token = authHeader.substring(this.tokenHead.length());
      String account = JwtTokenUtil.getUserNameFromToken(token, salt);
      if(StringUtil.isBlank(account)){
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.LOGOUT_NOTICE)), Constants.RESPONSE_STATUS);
        return false;
      }

      if(cacheManger.isLogout(token)){
        ResponseUtils.returnJson(response, JSONObject.toJSONString(RestResponse.failure(GenericCode.LOGOUT_NOTICE)), Constants.RESPONSE_STATUS);
        return false;
      }
      request.setAttribute(Constant.DEFAULT_REQUEST_PERMISSION, account);
      request.setAttribute(jwtTokenHeader, token);
      return true;
    }catch(Exception e){
      log.error("登陆拦截器 异常", e);
      return false;
    }
  }
}
